package org.dant.ant.extension.net.processors;

import java.util.*;
import org.apache.tools.ant.*;
import java.io.*;

public class AntCall {
  protected Map userProperties;
  protected Map sysProperties;
  protected RemoteLogger logger;
  Project project = new Project();
  
  public AntCall() {
  }

  private void registerLogger(String target) {
    logger = new RemoteLogger();
    logger.setTarget(target);
    logger.setErrorPrintStream(System.err);
    logger.setOutputPrintStream(System.out);
    project.addBuildListener(logger);
  }
  
  private void init(File buildFile) {
    project.init();
    try {
      Class.forName("javax.xml.parsers.SAXParserFactory");
      ProjectHelper.configureProject(project, buildFile);
    } catch (Throwable t) {
      t.printStackTrace();
      throw new BuildException(t);
    }
  }

  public String executeTarget(File buildFile) {
    init(buildFile);
    String defaultTarget = "all";
    defaultTarget = project.getDefaultTarget();
    System.out.println("Executing the default target: " + defaultTarget);
    registerLogger(defaultTarget);
    project.executeTarget(defaultTarget);
    return logger.getOutBuffer().toString();
  }

  public String executeTarget(File buildFile, String target) {
    init(buildFile);
    if (target == null || target.trim().equals("")) target = project.getDefaultTarget();
    registerLogger(target);
    project.executeTarget(target);
    return logger.getOutBuffer().toString();
  }

  public void setUserProperties(Map newProperties) {
    if (newProperties == null) return;
    Iterator e = newProperties.keySet().iterator();
    while (e.hasNext()) {
      String arg = (String)e.next();
      String value = (String)newProperties.get(arg);
      project.setUserProperty(arg, value);
    }
  }

  public void setSysProperties(Map newProperties) {
    if (newProperties == null) return;
    Iterator e = newProperties.keySet().iterator();
    while (e.hasNext()) {
      String arg = (String)e.next();
      String value = (String)newProperties.get(arg);
      project.setProperty(arg, value);
    }
  }
}
